<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\QrCodeController;
use App\Http\Controllers\TempInfo;
use App\Http\Controllers\TempInfoController;
use App\Models\ActivityApply;
use App\Models\ActivitySign;
use App\Models\ActivityTag;
use App\Models\Manage;
use App\Models\UserInfo;
use App\Models\UserLibraryInfo;
use App\Models\UserWechatInfo;
use Exception;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Exp;

/**
 * 活动标签类
 */
class ActivityController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\Activity();
        $this->validate = new  \App\Validate\ActivityValidate();
    }

    /**
     * 获取报名参数
     */
    public function getActivityApplyParam()
    {
        $data = $this->model->getActivityApplyParam();
        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     * @param start_time datetime 活动开始时间    数据格式  年月日
     * @param end_time datetime 活动结束时间
     * @param is_recom 是否热门活动  0或空表示全部  1 是  2 否 （默认）
     * @param is_apply 是否需要报名 1.是  2.否  默认1
     * @param is_play 是否发布 1.是  2.否  默认1
     * @param type_id 活动类型筛选   0或空表示全部
     * @param create_start_time datetime 活动创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 活动创建结束时间
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $create_start_time = $this->request->create_start_time;
        $create_end_time = $this->request->create_end_time;
        $type_id = $this->request->type_id;
        $is_apply = $this->request->is_apply;
        $is_play = $this->request->is_play;
        $is_recom = $this->request->is_recom;

        $res = $this->model->lists($keywords, $type_id, $start_time, $end_time, $create_start_time, $create_end_time, $is_apply, $is_recom, $is_play, null, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $activityApplyModel = new ActivityApply();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
            $res['data'][$key]['type_tag'] = ActivityTag::getTagNameByTagId($val['tag_id']);
            $res['data'][$key]['state'] = $this->model->getActListState($val);
            $res['data'][$key]['address'] = $val['province'] . $val['city'] . $val['district'] . $val['address'];
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            $res['data'][$key]['type_name'] = !empty($val['con_type']['type_name']) ?  $val['con_type']['type_name'] : '';

            //获取未审核数量
            $res['data'][$key]['uncheck_number'] = $activityApplyModel->getUncheckedActivityNumber($val['id']);

            unset($res['data'][$key]['con_type']);
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 活动id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;

        $res = $this->model->with('conType')->where('id', $id)->where('is_del', 1)->first();

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $res['tag_name'] = ActivityTag::getTagNameByTagId($res->tag_id); //获取活动标签

        $real_info_array = $this->model->getActivityApplyParam();
        $res->real_info_value = $this->getRealInfoArray($res->real_info, $real_info_array, 'value');
        $res->real_info_value = join("|", $res->real_info_value);

        //判断是否可以更改是否需要绑定读者证，有人报名就不允许修改
        $apply_status = $this->model->actIsApply($id);
        $res->is_can_is_reader = $apply_status ? false : true; //false 有人报名，不允许修改

        $res->start_time = $res->start_time ? date("Y/m/d", strtotime($res->start_time)) : null;
        $res->end_time = $res->end_time ? date("Y/m/d", strtotime($res->end_time)) : null;
        $res->apply_start_time = $res->apply_start_time ? date("Y/m/d H:i:s", strtotime($res->apply_start_time)) : null;
        $res->apply_end_time = $res->apply_end_time ? date("Y/m/d H:i:s", strtotime($res->apply_end_time)) : null;
        $res->cancel_end_time = $res->cancel_end_time;

        $res->type_name = !empty($res->conType['type_name']) ?  $res->conType['type_name'] : '';
        unset($res->conType);

        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param is_long int 是否是长期活动   1.是   2.否 默认2
     * @param is_apply int 是否需要报名 1.是  2.否  默认1
     * @param is_check int 报名是否需要审核   1.是   2.否(默认）
     * @param is_qr int 是否需要二维码进场   1.是   2.否(默认）
     * @param is_reader int 报名是否需要绑定读者证   1.是   2.否(默认）
     * @param is_continue 取消报名后是否可以继续报名   1.是   2.否(默认）
     * @param is_real int 是否需要用户真实信息 1需要 2不需要 默认2
     * @param astrict_sex int 性别限制   1.限男性  2.限女性  3.不限(默认)
     * @param type_id int 活动类型
     * @param tag_id int 活动标签  多个 逗号 拼接
     * @param real_info string 需要验证的真实信息id用|连接起来   1、姓名   2 、身份证号码  3、电话号码   4、读者证号码    5、真实人物头像   6、备注  7 单位名称 8 性别 9 年龄  10、附件 11、学校  12、年级  13、班级  14、微信号
     * @param title string 活动名称
     * @param img string 活动封面
     * @param intro mediumtext 活动内容
     * @param number int 活动名额
     * @param province string 省    选填
     * @param city string 市           选填
     * @param district string 区(县)      选填
     * @param address string 详细地址      选填
     * @param contacts string 联系人
     * @param tel string 联系电话
     * @param link string 跳转链接
     * @param start_age int 开始年龄  默认0   两个都是 0 则表示不需要年龄限制
     * @param end_age int 结束年龄  默认0   两个都是 0 则表示不需要年龄限制
     * @param apply_start_time datetime 活动报名开始时间
     * @param apply_end_time datetime 活动报名结束时间
     * @param everyday_start_time datetime 活动每日开始时间段
     * @param everyday_end_time datetime 活动每日结束时间段
     * @param start_time datetime 活动开始时间段
     * @param end_time datetime 活动结束时间段
     * @param cancel_end_time datetime 用户可取消时间限制   单位分钟
     * @param is_recom int  是否推荐为 热门活动  1 是  2 否 （默认）
     * @param sign_way int 扫码方式  1 、2者都可以  2、用户自主扫码  3、管理员设备扫码
     * @param is_play 是否发布 1.发布 2.未发布    默认1
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $is_exists = $this->model->nameIsExists($this->request->title, 'title');

        if ($is_exists) {
            return $this->returnApi(202, "该活动名称已存在");
        }


        if ($this->request->is_real == 1 && !$this->request->real_info) {
            return $this->returnApi(201, "请选择用户需要填写的真实信息");
        }

        if ($this->request->is_apply == 1 && !empty($this->request->link)) {
            return $this->returnApi(201, "跳转链接，必须是不需要报名的活动才能存在");
        }
        if (!empty($this->request->link)) {
            if (config('other.project_type') == 'applet'  && strtolower(substr($this->request->link, 0, 5)) !== 'https') {
                return $this->returnApi(201, "跳转链接必须是https开头");
            } elseif (config('other.project_type') == 'wechat'  && (strtolower(substr($this->request->link, 0, 4)) !== 'http' && strtolower(substr($this->request->link, 0, 5)) !== 'https')) {
                return $this->returnApi(201, "跳转链接必须是http或https开头");
            }
        }

        if ($this->request->is_apply == 1 && (!$this->request->apply_start_time || !$this->request->apply_end_time)) {
            return $this->returnApi(201, "请填写活动报名时间");
        }
        if ($this->request->is_apply == 1 && $this->request->apply_end_time > $this->request->start_time) {
            return $this->returnApi(201, "报名结束时间不能大于活动开始时间");
        }

        /*根据是否为长期活动处理数据*/
        if ($this->request->is_long == 1) {
            if (!$this->request->everyday_start_time || !$this->request->everyday_start_time) {
                return $this->returnApi(201, "每日活动时间不能为空");
            }
        } else {
            $this->request->merge(['everyday_start_time' => date("H:i:s", strtotime($this->request->start_time))]);
            $this->request->merge(['everyday_end_time' => date("H:i:s", strtotime($this->request->end_time))]);
        }


        $qrCodeObj = new QrCodeController();
        $sign_qr_code = $qrCodeObj->getQrCode('activity', 'sign_qr_code');
        if ($sign_qr_code === false) {
            return $this->returnApi(201, "添加失败，请重新添加");
        }
        //生成二维码
        $sign_qr_url = $qrCodeObj->setQr($sign_qr_code, true, 300, 1, [0, 0, 0]);

        /*生成经纬度*/
        // if (!empty($this->request->province) && !empty($this->request->city) && !empty($this->request->district) && !empty($this->request->address)) {
        //     $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
        //     if (is_string($map)) {
        //         return $this->returnApi(202, $map);
        //     }
        // } else {
        $map['lon'] = null;
        $map['lat'] = null;
        // }
        //处理报名参数
        list($is_real, $real_info) = $this->model->disRealInfo($this->request->all());

        $real_info_arr = explode('|', $real_info);
        if (in_array(2, $real_info_arr) || in_array(8, $real_info_arr) && $this->request->astrict_sex) {
            $astrict_sex = $this->request->astrict_sex;
        } else {
            $astrict_sex = 3;
        }
        if (in_array(2, $real_info_arr) || in_array(9, $real_info_arr) && $this->request->start_age) {
            $start_age = $this->request->start_age;
        } else {
            $start_age = 0;
        }
        if (in_array(2, $real_info_arr) || in_array(9, $real_info_arr) && $this->request->end_age) {
            $end_age = $this->request->end_age;
        } else {
            $end_age = 0;
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'is_long' => $this->request->is_long,
                'is_apply' => $this->request->is_apply,
                'is_check' => $this->request->is_check,
                'is_reader' => $this->request->is_reader ? $this->request->is_reader : 2,
                'type_id' => $this->request->type_id,
                'tag_id' => $this->request->tag_id,
                'is_qr' => $this->request->is_qr,
                'is_continue' => $this->request->is_continue,
                'astrict_sex' => $astrict_sex,
                'is_real' => $is_real,
                'real_info' => $real_info,
                'title' => $this->request->title,
                'img' => $this->request->img ? $this->request->img : 'default/default_activity.png',
                'intro' => $this->request->intro,
                'number' => ($this->request->number &&  $this->request->is_apply == 1) ? intval($this->request->number) : 0,
                'province' => $this->request->province,
                'city' => $this->request->city,
                'district' => $this->request->district,
                'street' => $this->request->street,
                'address' => $this->request->address,
                'contacts' => $this->request->contacts,
                'tel' => $this->request->tel,
                'link' => $this->request->link,
                'start_age' => $start_age,
                'end_age' => $end_age,
                'apply_start_time' => ($this->request->is_apply == 1 && $this->request->apply_start_time) ? $this->request->apply_start_time : null,
                'apply_end_time' => ($this->request->is_apply == 1 && $this->request->apply_end_time) ? $this->request->apply_end_time : null,
                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'everyday_start_time' => $this->request->everyday_start_time,
                'everyday_end_time' => $this->request->everyday_end_time,
                'cancel_end_time' => $this->request->cancel_end_time,
                'is_recom' => $this->request->is_recom,
                'is_play' => $this->request->is_play ? $this->request->is_play : 2,
                'sign_way' => $this->request->sign_way ? $this->request->sign_way : 2,
                'sign_qr_code' => $sign_qr_code,
                'sign_qr_url' => $sign_qr_url,
                'lon' => $map['lon'],
                'lat' => $map['lat'],
                'manage_id' => $this->request->manage_id,
            ];

            $this->model->add($data);

            // $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pActivity/activityDetail/index?act_id=' . $this->model->id; //活动二维码的链接  扫码跳转活动详情
            // $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1, [0, 0, 0], 'L'); //减小容错，让二维码更简单
            // $this->model->where('id', $this->model->id)->update(['qr_url' => $qr_url, 'qr_code' => $this->model->id]);

            //小程序二维码
            $applet_url = $qrCodeObj->getAppletDataVisitUrl(); //要和  qr_code 进行拼接
            $applet_qr_code_url = $applet_url . $this->model->id . '&s=activity_detail'; //跳转地址 活动详情
            $applet_qr_url = $qrCodeObj->setQr($applet_qr_code_url, true, 300, 1, [0, 0, 0]);
            $this->model->where('id', $this->model->id)->update(['qr_url' => $applet_qr_url, 'qr_code' => $this->model->id]);

            //
            // if ($is_push == 1) {
            //     //添加推送消息
            //     $tempInfoObj = new TempInfoController();
            //     //添加活动报名提醒
            //     $data['content'] = '新活动发布啦，快来看看吧！';
            //     $data['type_name'] = '读者活动';
            //     $data['time'] = substr($this->request->start_time, 0, 10) . '~' . substr($this->request->end_time, 0, 10);
            //     $data['remark'] = '活动名称：' . $this->request->title;
            //     $data['link'] = config('other.activity_new_issue') . '?act_id=' . $act_id;

            //     $user_open_id = UserWechatInfo::select('open_id')->get();
            //     //$user_open_id = [['open_id'=>'ouGi1s-KA5mvxl3UIOFciI9MrsGg']]; //测试 open_id
            //     foreach ($user_open_id as $key => $val) {
            //         //添加推送模板消息
            //         $data['openid'] = $val['open_id'];
            //         $tempInfoObj->sendServiceInfo($data);
            //     }
            // }
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "保存成功", true);
        } catch (\Exception $e) {
            //   var_dump($e->getMessage());exit;
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "保存失败" . $e->getMessage());
        }
    }



    /**
     * 编辑
     * @param id int 活动id
     * @param is_long int 是否是长期活动   1.是   2.否 默认2
     * @param is_apply int 是否需要报名 1.是  2.否  默认1
     * @param is_check int 报名是否需要审核   1.是   2.否(默认）
     * @param is_reader int 报名是否需要绑定读者证   1.是   2.否(默认） 必须绑定
     * @param is_qr int 是否需要二维码进场   1.是   2.否(默认）
     * @param is_continue 取消报名后是否可以继续报名   1.是   2.否(默认）
     * @param is_real int 是否需要用户真实信息 1需要 2不需要 默认2
     * @param astrict_sex int 性别限制   1.限男性  2.限女性  3.不限(默认)
     * @param real_info string 需要验证的真实信息id用|连接起来   1、姓名   2 、身份证号码  3、电话号码   4、读者证号码    5、真实人物头像   6、备注  7 单位名称 8 性别 9 年龄  10、附件  11、学校  12、年级  13、班级  14、微信号
     * @param type_id int 活动类型
     * @param tag_id int 活动标签  多个 逗号 拼接
     * @param title string 活动名称
     * @param img string 活动封面
     * @param intro mediumtext 活动内容
     * @param number int 活动名额
     * @param province string 省           选填
     * @param city string 市               选填
     * @param district string 区(县)       选填
     * @param address string 详细地址      选填
     * @param contacts string 联系人
     * @param tel string 联系电话
     * @param link string 跳转链接
     * @param start_age int 开始年龄  默认0   两个都是 0 则表示不需要年龄限制
     * @param end_age int 结束年龄  默认0   两个都是 0 则表示不需要年龄限制
     * @param apply_start_time datetime 活动报名开始时间
     * @param apply_end_time datetime 活动报名结束时间
     * @param everyday_start_time datetime 活动每日开始时间段
     * @param everyday_end_time datetime 活动每日结束时间段
     * @param start_time datetime 活动开始时间段
     * @param end_time datetime 活动结束时间段
     * @param cancel_end_time datetime 用户可取消时间限制 单位分钟
     * @param is_recom int  是否推荐为 热门活动  1 是  2 否 （默认）
     * @param sign_way int 扫码方式  1 、2者都可以  2、用户自主扫码  3、管理员设备扫码
     * @param is_play 是否发布 1.发布 2.未发布    默认1
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->title, 'title', $this->request->id);

        if ($is_exists) {
            return $this->returnApi(202, "该活动名称已存在");
        }

        if ($this->request->is_real == 1 && !$this->request->real_info) {
            return $this->returnApi(201, "请选择用户需要填写的真实信息");
        }

        if ($this->request->is_apply == 1 && !empty($this->request->link)) {
            return $this->returnApi(201, "跳转链接，必须是不需要报名的活动才能存在");
        }
        if (!empty($this->request->link)) {
            if (config('other.project_type') == 'applet'  && strtolower(substr($this->request->link, 0, 5)) !== 'https') {
                return $this->returnApi(201, "跳转链接必须是https开头");
            } elseif (config('other.project_type') == 'wechat'  && (strtolower(substr($this->request->link, 0, 4)) !== 'http' && strtolower(substr($this->request->link, 0, 5)) !== 'https')) {
                return $this->returnApi(201, "跳转链接必须是http或https开头");
            }
        }

        if ($this->request->is_apply == 1 && (!$this->request->apply_start_time || !$this->request->apply_end_time)) {
            return $this->returnApi(201, "请填写活动报名时间");
        }
        if ($this->request->is_apply == 1 && $this->request->apply_end_time > $this->request->start_time) {
            return $this->returnApi(201, "报名结束时间不能大于活动开始时间");
        }


        $id = $this->request->id;
        $activity = $this->model->where('id', $id)->where('is_del', 1)->first();

        //允许带有Copy的修改活动信息，不允许修改活动信息
        if ($activity['end_time'] < date('Y-m-d H:i:s') && (strpos($activity['title'], 'Copy') === false && strpos($this->request->title, 'Copy') === false)) {
            return $this->returnApi(201, "活动已结束，不允许修改活动信息");
        }

        if (!$activity) {
            return $this->returnApi(201, "参数传递错误");
        }

        if ($activity->is_play == 1) {
            return $this->returnApi(201, "请先撤销，在进行修改！");
        }


        //已有用户报名，不允许修改
        if ($activity->is_reader !=  $this->request->is_reader) {
            //判断是否有人报名
            $apply_status = $this->model->actIsApply($id);
            if ($apply_status) {
                return $this->returnApi(201, "已有用户报名，不能修改是否需要绑定读者证参数");
            }
        }
        /*生成经纬度*/
        // if (
        //     !empty($this->request->province) && !empty($this->request->city) && !empty($this->request->district) && !empty($this->request->address)
        //     && $this->request->province . $this->request->city . $this->request->district . $this->request->address != $activity->province . $activity->city . $activity->district . $activity->address
        // ) {
        //     $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
        //     if (is_string($map)) {
        //         return $this->returnApi(202, $map);
        //     }
        // } else {
        $map['lon'] = null;
        $map['lat'] = null;
        // }
        /*根据是否为长期活动处理数据*/
        if ($this->request->is_long == 1) {
            if (!$this->request->everyday_start_time || !$this->request->everyday_start_time) {
                return $this->returnApi(201, "每日活动时间不能为空");
            }
        } else {
            $this->request->merge(['everyday_start_time' => date("H:i:s", strtotime($this->request->start_time))]);
            $this->request->merge(['everyday_end_time' => date("H:i:s", strtotime($this->request->end_time))]);
        }

        $old_img = $activity->img;

        //处理报名参数
        list($is_real, $real_info) = $this->model->disRealInfo($this->request->all());

        $real_info_arr = explode('|', $real_info);
        if (in_array(2, $real_info_arr) || in_array(8, $real_info_arr) && $this->request->astrict_sex) {
            $astrict_sex = $this->request->astrict_sex;
        } else {
            $astrict_sex = 3;
        }
        if (in_array(2, $real_info_arr) || in_array(9, $real_info_arr) && $this->request->start_age) {
            $start_age = $this->request->start_age;
        } else {
            $start_age = 0;
        }
        if (in_array(2, $real_info_arr) || in_array(9, $real_info_arr) && $this->request->end_age) {
            $end_age = $this->request->end_age;
        } else {
            $end_age = 0;
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'id' => $this->request->id,
                'is_long' => $this->request->is_long,
                'is_apply' => $this->request->is_apply,
                'is_check' => $this->request->is_check,
                'is_reader' => $this->request->is_reader ? $this->request->is_reader : 2,
                'type_id' => $this->request->type_id,
                'tag_id' => $this->request->tag_id,
                'is_qr' => $this->request->is_qr,
                'is_continue' => $this->request->is_continue,
                'astrict_sex' => $astrict_sex,
                'is_real' => $is_real,
                'real_info' => $real_info,
                'title' => $this->request->title,
                'link' => $this->request->link,
                'img' => $this->request->img ? $this->request->img : 'default/default_activity.png',
                'intro' => $this->request->intro,
                'number' => ($this->request->number  &&  $this->request->is_apply == 1) ? intval($this->request->number) : 0,
                'province' => $this->request->province,
                'city' => $this->request->city,
                'district' => $this->request->district,
                'street' => $this->request->street,
                'address' => $this->request->address,
                'contacts' => $this->request->contacts,
                'tel' => $this->request->tel,
                'start_age' => $start_age,
                'end_age' => $end_age,
                'apply_start_time' => ($this->request->is_apply == 1 && $this->request->apply_start_time) ? $this->request->apply_start_time : null,
                'apply_end_time' => ($this->request->is_apply == 1 && $this->request->apply_end_time) ? $this->request->apply_end_time : null,
                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'is_recom' => $this->request->is_recom,
                'sign_way' => $this->request->sign_way ? $this->request->sign_way : 2,
                'lon' => $map['lon'],
                'lat' => $map['lat'],
                'everyday_start_time' => $this->request->everyday_start_time,
                'everyday_end_time' => $this->request->everyday_end_time,
                'cancel_end_time' => $this->request->cancel_end_time,
                'is_play' => $this->request->is_play ? $this->request->is_play : 2,
                'change_time' => date("Y-m-d H:i:s", time())
            ];

            if (empty($activity['qr_url'])) {
                $activity_id = $activity['id'];
                // $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pActivity/activityDetail/index?act_id=' . $activity_id; //活动二维码的链接  扫码跳转活动详情
                $qrCodeObj = new QrCodeController();
                // $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1, [0, 0, 0], 'L'); //减小容错，让二维码更简单

                //  $applet_qr_code = $qrCodeObj->getQrCode('activity_detail', 'qr_code');
                $applet_url = $qrCodeObj->getAppletDataVisitUrl(); //要和  qr_code 进行拼接
                $applet_qr_code_url = $applet_url . $activity_id . '&s=activity_detail'; //跳转地址 活动详情
                $applet_qr_url = $qrCodeObj->setQr($applet_qr_code_url, true, 360, 1, [0, 0, 0], 'L');

                $data['qr_url'] = $applet_qr_url;
                $data['qr_code'] = $activity_id;
            }

            if (empty($activity['sign_qr_url'])) {
                $qrCodeObj = new QrCodeController();
                if (empty($activity['sign_qr_code'])) {
                    $sign_qr_code = $qrCodeObj->getQrCode('activity', 'sign_qr_code');
                    if ($sign_qr_code === false) {
                        throw new Exception("添加失败，请重新添加");
                    }
                    $data['sign_qr_code'] = $sign_qr_code;
                } else {
                    $sign_qr_code = $activity['sign_qr_code'];
                }
                //生成二维码
                $sign_qr_url = $qrCodeObj->setQr($sign_qr_code, true, 300, 1, [0, 0, 0]);
                $data['sign_qr_url'] = $sign_qr_url;
            }
            $this->model->change($data);

            //删除旧资源 copy 图片有问题，不删除
            // if ($old_img != $this->request->img && $old_img != 'default/default_activity.png') {
            //     $this->deleteFile($old_img);
            // }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "保存成功", true);
        } catch (\Exception $e) {
            // dd($e->getMessage());
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 活动id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $activityApplyObj = new ActivityApply();
        $unchecked_number = $activityApplyObj->getUncheckedActivityNumber($this->request->id);
        if (!empty($unchecked_number)) {
            return $this->returnApi(202, "此活动已有用户参与，不允许删除!");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }


    /**
     * 撤销
     * @param id int 活动id
     */
    public function cancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->cancelAndRelease($this->request->id, 2);

        if ($res === true) {
            return $this->returnApi(200, "撤销成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 发布
     * @param id int 活动id
     */
    public function release()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('release')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->cancelAndRelease($this->request->id, 1);

        if ($res === true) {
            return $this->returnApi(200, "发布成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 签到
     * @param id int 活动id
     * @param apply_id int 申请记录id （与code 2选一）
     * @param type string 若值为：code   则是 二维码签到模式   则 code值必须要有
     * @param code string 二维码值或者读者证号
     */
    public function sign()
    {
        $applyModel = new ActivityApply();
        //处理逾期未签到的数据
        $applyModel->checkApplyStatus();

        //增加验证场景进行验证
        if (!$this->validate->scene('sign')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $act_id = $this->request->id;
        $apply_id = $this->request->apply_id;

        $signModel = new ActivitySign();
        if ($this->request->type == 'code') {
            $code = $this->request->code;
            if (empty($code)) {
                return $this->returnApi(202, "请先扫描二维码");
            }
            $code_data = $this->dataDecrypt($code);
            if (empty($code_data) || empty($code_data['node']) || empty($code_data['apply_id']) || empty($code_data['expire_time']) || $code_data['node'] != 'activity') {
                return $this->returnApi(202, "无效二维码");
            }
            if ($code_data['expire_time'] < date('Y-m-d H:i:s')) {
                return $this->returnApi(202, "二维码已过期");
            }
            $apply_id = $code_data['apply_id'];
        }
        if (empty($apply_id)) {
            return $this->returnApi(201, "参数错误");
        }

        $apply_info = $applyModel->where('id', $apply_id)->where('act_id', $act_id)->first();
        if (!$apply_info) {
            return $this->returnApi(201, "参数传递错误");
        }
        // 活动是否存在
        $act_info = $this->model->select('id', 'title', 'is_apply', 'is_long', 'start_time', 'end_time', 'everyday_start_time', 'everyday_end_time', 'sign_way')
            ->where("id", $apply_info->act_id)
            ->where("is_del", 1)
            ->where("is_play", 1)
            ->first();

        if (empty($act_info)) return $this->returnApi(201, "活动不存在或已被删除");
        if ($act_info['end_time'] < date("Y-m-d", strtotime("-1 days"))) return $this->returnApi(201, "活动已经结束很久了，不能进行签到");
        //  if ($act_info['sign_way'] == 2) return '请使用扫码功能进行扫码操作';

        if ($act_info['is_long'] == 1) {
            //长期活动，每日签到
            $sign = $signModel->where('date', date("Y-m-d", time()))->where('apply_id', $apply_id)->where('act_id', $act_id)->first();
            if ($sign) {
                return $this->returnApi(202, "您今日已签到，请勿重复签到！");
            }
        } else {
            $sign = $signModel->where('apply_id', $apply_id)->where('act_id', $act_id)->first();
            if ($sign) {
                return $this->returnApi(202, "您已签到，请勿重复签到！");
            }
        }
        $date = date("Y-m-d H:i:s", time());
        $signModel->act_id = $act_id;
        $signModel->apply_id = $apply_info->id;
        $signModel->user_id = $apply_info->user_id;
        $signModel->date = date("Y-m-d", strtotime($date));
        $signModel->yyy = date("Y", strtotime($date));
        $signModel->mmm = date("m", strtotime($date));
        $signModel->ddd = date("d", strtotime($date));

        // 启动事务
        DB::beginTransaction();;
        try {
            $signModel->save();
            $apply_info->sign_num++;
            $apply_info->save();

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "签到成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "签到失败");
        }
    }
    /**
     * 切换类型
     * @param id int 活动id
     * @param type_id int 类型id
     */
    public function switchoverType()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('switchover_type')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->switchoverType($this->request->id, $this->request->type_id);

        if ($res === true) {
            return $this->returnApi(200, "切换成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 推荐为热门活动 或 取消热门推荐
     * @param id  活动id
     */
    public function recomAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('recom_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        list($code, $msg) = $this->model->recomAndCancel($this->request->id);

        if ($code === 200) {
            return $this->returnApi(200, $msg, true);
        }
        return $this->returnApi($code, $msg);
    }


    /**
     * 活动推送 发送模板消息给用户
     * @param id 活动id
     */
    public function push()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('push')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;
        $activity = $this->model->where('id', $id)->where('is_del', 1)->first();

        if (!$activity) {
            return $this->returnApi(201, "参数传递错误");
        }

        if ($activity->push_num > 3) {
            return $this->returnApi(201, "此活动推送次数过多，请勿继续推送");
        }

        //添加推送消息
        $tempInfoObj = new TempInfoController();
        //添加活动报名提醒
        $data['content'] = '新活动发布啦，快来看看吧！';
        $data['type_name'] = '读者活动';
        $data['time'] = substr($activity->start_time, 0, 10) . '~' . substr($activity->end_time, 0, 10);
        $data['remark'] = '活动名称：' . $activity->title;
        $data['link'] = config('other.activity_new_issue') . '?act_id=' . $id;
        $user_open_id = UserWechatInfo::select('open_id')->get();
        //  $user_open_id = [['open_id'=>'ouGi1s-KA5mvxl3UIOFciI9MrsGg']]; //测试 open_id
        foreach ($user_open_id as $key => $val) {
            //添加推送模板消息
            $data['openid'] = $val['open_id'];
            $tempInfoObj->sendServiceInfo($data);
        }
        $activity->push_num = ++$activity->push_num;
        $activity->save();

        return $this->returnApi(200, "推送成功", true);
    }

    /**
     * 复制活动
     * @param id 活动id
     * @param password  管理员密码
     */
    public function copyData()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('copy_data')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断管理员密码是否正确
        $is_success = Manage::passwordIsSuccess($this->request->manage_id, $this->request->password);
        if (!$is_success) {
            return $this->returnApi(202, '密码输入错误');
        }
        $res = $this->model->where('id', $this->request->id)->where('is_del', 1)->first();
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $res = $res->toArray();
        unset($res['id']);
        unset($res['browse_num']);
        unset($res['create_time']);
        unset($res['change_time']);
        unset($res['qr_code']);
        unset($res['qr_url']);

        $qrCodeObj = new QrCodeController();
        $sign_qr_code = $qrCodeObj->getQrCode('activity', 'sign_qr_code');
        if ($sign_qr_code === false) {
            return $this->returnApi(201, "添加失败，请重新添加");
        }
        //生成二维码
        $sign_qr_url = $qrCodeObj->setQr($sign_qr_code, true, 300, 1, [0, 0, 0]);

        DB::beginTransaction();
        try {
            $res['title'] = $res['title'] . ' Copy'; //加上一个复制的标识
            $res['manage_id'] = $this->request->manage_id;
            $res['is_play'] = 2; //默认未发布
            $res['sign_qr_code'] = $sign_qr_code;
            $res['sign_qr_url'] = $sign_qr_url;
            $res['apply_number'] = 0;
            $this->model->add($res);

            //小程序二维码
            //   $applet_qr_code = $qrCodeObj->getQrCode('activity_detail', 'qr_code');
            $applet_url = $qrCodeObj->getAppletDataVisitUrl(); //要和  qr_code 进行拼接
            $applet_qr_code_url = $applet_url . $this->model->id . '&s=activity_detail'; //跳转地址 活动详情
            $applet_qr_url = $qrCodeObj->setQr($applet_qr_code_url, true, 300, 1, [0, 0, 0]);
            $this->model->where('id', $this->model->id)->update(['qr_url' => $applet_qr_url, 'qr_code' => $this->model->id]);

            // $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pActivity/activityDetail/index?act_id=' . $this->model->id; //活动二维码的链接  扫码跳转活动详情
            // $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1, [0, 0, 0], 'L'); //减小容错，让二维码更简单
            // $this->model->where('id', $this->model->id)->update(['qr_url' => $qr_url, 'qr_code' => $this->model->id]);


            DB::commit();
            return $this->returnApi(200, "复制成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "复制失败");
        }
    }
}
